package com.example.student_blocket;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;

public class AddAdActivity extends Activity implements View.OnClickListener{
	@SuppressWarnings("unused")
	private InputStream is = null;
	private final String UPLOAD_IMAGE = Singleton.getInstance().getHOST() + "shop-app/upload-image.php";
	private final String CREATE_AD = Singleton.getInstance().getHOST() + "shop-app/create-an-ad.php";
	private final String SELECT_CATEGORY = Singleton.getInstance().getHOST() + "shop-app/select-categories.php";
	private final String SET_IMAGE = Singleton.getInstance().getHOST() + "shop-app/set-ad-image.php";
	private ArrayList<String> categories = new ArrayList<String>();
	private ImageButton ib;
	private ImageView iv;
	private Intent i;
	final static int cameraData = 0;
	private Bitmap bmp;
	private Button btnPublish;
	private Button btnCategory;
	private EditText titleInput;
	private EditText priceInput;
	private EditText descriptionInput;
	private String categoryInput = "";
	private boolean hasCustomImage = false;
	private final Misc misc = new Misc();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.add_ad_activity);
		initialize();
		InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
		bmp = BitmapFactory.decodeStream(is);
	}
	
	private void initialize() {
		iv = (ImageView) findViewById(R.id.ivReturnedPic);
		ib = (ImageButton) findViewById(R.id.ibTakePic);
		titleInput = (EditText) findViewById(R.id.addAdTitleInput);
		priceInput = (EditText) findViewById(R.id.addAdPriceInput);
		descriptionInput = (EditText) findViewById(R.id.addAdDescriptionInput);
		btnCategory = (Button) findViewById(R.id.btnCategory);
		btnPublish = (Button) findViewById(R.id.btnPublishAd);
		
		ib.setOnClickListener(this);
		btnCategory.setOnClickListener(this);
		btnPublish.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch(view.getId()){
		case R.id.ibTakePic:
			i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(i, cameraData);
			break;
		case R.id.btnCategory:
			new getCategories().execute();
			break;
		case R.id.btnPublishAd:
			if (misc.validateInput(categoryInput)
					&& misc.validateInput(descriptionInput.getText().toString())
					&& misc.validateInput(priceInput.getText().toString())
					&& misc.validateInput(titleInput.getText().toString())) {
				new AddAnAd().execute();
			} else{
				if (!misc.validateInput(titleInput.getText().toString())){
					misc.showErrorMessage("The title of the ad is empty!", getApplicationContext());
				} else if (!misc.validateInput(priceInput.getText().toString())){
					misc.showErrorMessage("No price has been entered!", getApplicationContext());
				} else if (!misc.validateInput(descriptionInput.getText().toString())){
					misc.showErrorMessage("The description of the ad is empty!", getApplicationContext());
				} else if (!misc.validateInput(categoryInput)) {
					misc.showErrorMessage("No category has been selected!", getApplicationContext());
				} 
			}
			
			break;
		}
	}

	@Override
	public void onBackPressed() {
		startActivity(new Intent(AddAdActivity.this, AdsActivity.class));
		finish();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			Bundle extras = data.getExtras();
			bmp = (Bitmap) extras.get("data");
			hasCustomImage = true;
			iv.setImageBitmap(bmp);
		}
	}
	
	private class getCategories extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        
	        pDialog = new ProgressDialog(AddAdActivity.this);
	        pDialog.setMessage("Loading Categories...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(String... params) {
			boolean hasCategory = false;
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
			JSONObject json = jParser.makeHttpRequest(SELECT_CATEGORY, values);
			try {
                int success = json.getInt("affected");
 
                if (success == 1) {
                	JSONArray ads = json.getJSONArray("categories");
                    for (int i = 0; i < ads.length(); i++) {
                        JSONObject c = ads.getJSONObject(i);
                        String name = c.getString("name");
                        categories.add(name);
                    }
                    hasCategory = true;
                } else {
                	hasCategory = false;
                }
			} catch (JSONException e) {
                e.printStackTrace();
            }
	        return hasCategory;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				final String categoryArray[] = new String[categories.size()];
				
				for (int i = 0; i < categories.size(); i++) {
					categoryArray[i] = categories.get(i);
				}
		        final Dialog dialog = new Dialog(AddAdActivity.this);
		        dialog.setContentView(R.layout.dialog_categories);
		        dialog.setTitle("List Title");
		        ListView listView = (ListView) dialog.findViewById(R.id.listCategories);

		        ArrayAdapter<String> ad = new ArrayAdapter<String>(getApplicationContext(), R.layout.category_item, categoryArray);
		        listView.setAdapter(ad);

		        listView.setOnItemClickListener(new OnItemClickListener() {
		            @Override
		            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		            	categoryInput = categoryArray[position];
		                dialog.dismiss();
		            }
		        });

		        dialog.show();
		        //TODO
			} else {
				Log.e("ERROR", "ERROR in getCategory");
			}
			categories.clear();
			pDialog.dismiss();
        }
	}
	
	private class AddAnAd extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        
	        pDialog = new ProgressDialog(AddAdActivity.this);
	        pDialog.setMessage("Publishing...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(String... params) {
			boolean created;
			JSONParser jParser = new JSONParser();
			Date cDate = new Date();
			String usernameIn = Singleton.getInstance().getUsername();
			String titleIn = titleInput.getText().toString();
			String priceIn = priceInput.getText().toString();
			String descriptionIn = descriptionInput.getText().toString();
			String dateIn = new SimpleDateFormat("yyyy-MM-dd",Locale.US).format(cDate);
			String categoryIn = categoryInput;
			String soldIn = "0";
			Log.e("ATTENTION", usernameIn +"...."+ titleIn +"...."+ priceIn +"...."+ descriptionIn + dateIn +"...."+ categoryIn +"...."+ soldIn);
            List<NameValuePair> paras = new ArrayList<NameValuePair>();
            paras.add(new BasicNameValuePair("owner", usernameIn));
            paras.add(new BasicNameValuePair("title", titleIn));
            paras.add(new BasicNameValuePair("price", priceIn));
            paras.add(new BasicNameValuePair("description", descriptionIn));
            paras.add(new BasicNameValuePair("date", dateIn));
            paras.add(new BasicNameValuePair("category", categoryIn));
            paras.add(new BasicNameValuePair("sold", soldIn));
            
			JSONObject json = jParser.makeHttpRequest(CREATE_AD,paras);
			boolean added = false;
	        try {
				int result = json.getInt("affected");
				if (result == 1) {
					added = true;
				} else {
					added = false;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
	        String ap = null;
			try {
				ap = json.getString("message");
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
	        Log.e("ERROR",ap);
	        if (added) {
	        	if (hasCustomImage) {
	        		String adsID = null;
	        		try {
						adsID = json.getString("ad_id");
					} catch (JSONException e) {
						e.printStackTrace();
					}
	        		uploadImage(bmp, usernameIn, adsID);
	        		String imagePath = Singleton.getInstance().getHOST() + "shop-app/images/"+ usernameIn + "/image"+adsID+".jpg";
	        		List<NameValuePair> paras1 = new ArrayList<NameValuePair>();
	        		paras1.add(new BasicNameValuePair("image_path", imagePath));
	        		paras1.add(new BasicNameValuePair("username", usernameIn));
	        		paras1.add(new BasicNameValuePair("ad_id", adsID));
	        		JSONObject json1 = jParser.makeHttpRequest(SET_IMAGE,paras1);
					try {
						int result = json1.getInt("affected");
						if (result == 1) {
							Log.e("ERROR", "The image setup is good");
						} else {
							Log.e("ERROR", "The image setup is NOT OK");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					String adsID = null;
	        		try {
						adsID = json.getString("ad_id");
					} catch (JSONException e) {
						e.printStackTrace();
					}
					String imagePath = Singleton.getInstance().getHOST() + "shop-app/images/icon-no-image.png";
	        		List<NameValuePair> paras1 = new ArrayList<NameValuePair>();
	        		paras1.add(new BasicNameValuePair("image_path", imagePath));
	        		paras1.add(new BasicNameValuePair("username", usernameIn));
	        		paras1.add(new BasicNameValuePair("ad_id", adsID));
	        		JSONObject json1 = jParser.makeHttpRequest(SET_IMAGE,paras1);
					try {
						int result = json1.getInt("affected");
						if (result == 1) {
							Log.e("ERROR", "The image setup is good");
						} else {
							Log.e("ERROR", "The image setup is NOT OK");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
	        	created = true;
			} else {
				Log.e("ERROR", "ERROR in getCategory");
				created = false;
			}
	        return created;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				startActivity(new Intent(getApplicationContext(), AdsActivity.class));
				finish();
			} else {
				Log.e("ERROR", "ERROR in created");
			}
			pDialog.dismiss();
        }
	}
	
	private void uploadImage(Bitmap image, String username, String ad_id){
		
		Bitmap photo = image;
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		photo.compress(Bitmap.CompressFormat.JPEG, 90, bao);
		byte[] ba = bao.toByteArray();
		String ba1 = Base64.encodeToString(ba, Base64.DEFAULT);

		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("image",ba1));
		nameValuePairs.add(new BasicNameValuePair("username", username));
		nameValuePairs.add(new BasicNameValuePair("ad_id", ad_id));
		try {
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(UPLOAD_IMAGE);
		    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		    HttpResponse response = httpclient.execute(httppost);
		    HttpEntity entity = response.getEntity();
		    is = entity.getContent();
		} catch(Exception e){
		    Log.e("log_tag", "Error in http connection "+e.toString());
		}
		
		
	}
}
